

package com.hazelcast.client.map.impl.querycache.subscriber;

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.QueryCacheConfig;
import com.hazelcast.map.impl.querycache.QueryCacheConfigurator;
import com.hazelcast.map.impl.querycache.QueryCacheEventService;
import com.hazelcast.map.impl.querycache.subscriber.AbstractQueryCacheConfigurator;

import java.util.Map;

/**
 * Client side implementation of {@link QueryCacheConfigurator}.
 *
 * @see QueryCacheConfigurator
 */
public class ClientQueryCacheConfigurator extends AbstractQueryCacheConfigurator {

    private final ClientConfig clientConfig;
    private final ClassLoader classLoader;

    public ClientQueryCacheConfigurator(ClientConfig clientConfig, QueryCacheEventService eventService) {
        super(eventService);
        this.clientConfig = clientConfig;
        this.classLoader = clientConfig.getClassLoader();
    }

    @Override
    public QueryCacheConfig getOrCreateConfiguration(String mapName, String cacheName, String cacheId) {
        QueryCacheConfig config = clientConfig.getOrCreateQueryCacheConfig(mapName, cacheName);

        setPredicateImpl(config, classLoader);
        setEntryListener(mapName, cacheId, config, classLoader);

        return config;
    }

    @Override
    public QueryCacheConfig getOrNull(String mapName, String cacheName, String cacheId) {
        QueryCacheConfig config = clientConfig.getOrNullQueryCacheConfig(mapName, cacheName);
        if (config != null) {
            setPredicateImpl(config, classLoader);
            setEntryListener(mapName, cacheId, config, classLoader);
        }

        return config;
    }

    @Override
    public void removeConfiguration(String mapName, String cacheName) {
        Map<String, Map<String, QueryCacheConfig>> allQueryCacheConfig = clientConfig.getQueryCacheConfigs();
        Map<String, QueryCacheConfig> mapQueryCacheConfig = allQueryCacheConfig.get(mapName);
        if (mapQueryCacheConfig == null || mapQueryCacheConfig.isEmpty()) {
            return;
        }
        mapQueryCacheConfig.remove(cacheName);
    }

}
